package com.gprinter.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.czy1121.view.RoundButton;
import com.gprinter.bean.MyEvent;
import com.gprinter.http.API;
import com.gprinter.http.Files;
import com.gprinter.http.Okhttp;
import com.gprinter.utils.FullyGridLayoutManager;
import com.gprinter.utils.GridImageAdapter;
import com.gprinter.utils.Photo_Bean;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sample.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



public class TJ_Activity extends AppCompatActivity {

    @BindView(R.id.img_back)
    RelativeLayout imgBack;
    @BindView(R.id.textView11)
    TextView textView11;
    @BindView(R.id.bbhs)
    TextView bbhs;
    @BindView(R.id.textView7)
    TextView textView7;

    @BindView(R.id.layout_help)
    RelativeLayout layoutHelp;
    @BindView(R.id.editText)
    TextView editText;
    @BindView(R.id.xxxx)
    TextView xxxx;


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.qs)
    RoundButton qs;
    @BindView(R.id.activity_seetting)
    LinearLayout activitySeetting;
    GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int themeId;
    LocalMedia media;
    ArrayList<Photo_Bean> photo_been = new ArrayList<Photo_Bean>();
    String TAG = "TJ_Activity";
    String duijiema;
    String mingxiid;
    String dingdanhao;
    String id;
    String shangchuanyemianxianshiwenzi, tongxingzhi, httpipdizhi, chulileixingtype, yonghuid, canshu1, canshu2, canshu3, canshu4, canshu5;
    String dingdanzidingyibianhao;
    @BindView(R.id.checkBox_zp)
    CheckBox checkBoxZp;
    @BindView(R.id.checkBox_sp)
    CheckBox checkBoxSp;
    int check = 0;
    @BindView(R.id.layout_photo)
    RelativeLayout layout_photo;
//    @BindView(R.id.sp)
//    ImageView sp;
//    @BindView(R.id.layout_video)
//    LinearLayout layout_video;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo2);

        duijiema = getIntent().getStringExtra("key1");
        mingxiid = getIntent().getStringExtra("key2");
        dingdanhao = getIntent().getStringExtra("key3");
        dingdanzidingyibianhao = getIntent().getStringExtra("key4");
        shangchuanyemianxianshiwenzi = getIntent().getStringExtra("key5");

        tongxingzhi = getIntent().getStringExtra("key6");
        httpipdizhi = getIntent().getStringExtra("key7");
        chulileixingtype = getIntent().getStringExtra("key8");
        yonghuid = getIntent().getStringExtra("key9");
        canshu1 = getIntent().getStringExtra("key10");
        Log.e(TAG, "xx;"+canshu1);
        canshu2 = getIntent().getStringExtra("key11");
        canshu3 = getIntent().getStringExtra("key12");
        canshu4 = getIntent().getStringExtra("key13");
         canshu5 = getIntent().getStringExtra("key14");
//        LoginName = z_userInfoDao.query2().getLoginName();
        ButterKnife.bind(this);
        textView7.setText(dingdanhao);
        editText.setText(mingxiid);
        xxxx.setText(""+shangchuanyemianxianshiwenzi);
        initview();

    }

    // 取消注册
    @Override
    public void onDestroy() {
        super.onDestroy();


    }

    private void initview() {
        checkBoxZp.setChecked(true);
        checkBoxSp.setChecked(false);
        checkBoxZp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    check = 0;
                    checkBoxZp.setChecked(true);
                    checkBoxSp.setChecked(false);
                    selectList.clear();
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
//                    layout_video.setVisibility(View.GONE);
                    layout_photo.setVisibility(View.VISIBLE);
                }


            }
        });
        checkBoxSp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    check = 1;
                    checkBoxZp.setChecked(false);
                    checkBoxSp.setChecked(true);
                    selectList.clear();
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
//                    layout_video.setVisibility(View.VISIBLE);
                    layout_photo.setVisibility(View.GONE);
                }


            }
        });



        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(TJ_Activity.this, 4, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(TJ_Activity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(5);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivitysss.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(TJ_Activity.this).externalPicturePreview(position, selectList);
                            break;


                    }
                }
            }
        });


    }

    String st1; //缩略图
    String st2; //视频地址

//    public void onEventMainThread(MyEvent event) {
//        if (!TextUtils.isEmpty(event.getString1())) {
//            st1 = event.getString1();
//            Log.e(TAG, "xx" + st1);
//            st2 = event.getString2();
//            Log.e(TAG, "xx" + st2);
//            Bitmap bitmap = BitmapFactory.decodeFile(st1);
//            sp.setImageBitmap(bitmap);
//        }


//    }
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {


            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(TJ_Activity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(3)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(3)// 每行显示个数
                    .selectionMode(
                            PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
//                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .compressMode(PictureConfig.LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }


    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    Log.e("3344", "onActivityResult:" + selectList.size());
                    break;
            }

        } else {
            if (resultCode == 999) {
                Bundle b = data.getExtras(); //data为B中回传的Intent
                String str = b.getString("ewm");//str即为回传的值
                textView7.setText(str);
            }
        }
    }


    public void shangchuan() {
        for (int i = 0; i < selectList.size(); i++) {
            String compressPath = selectList.get(i).getCompressPath();
            Log.e(TAG, "xx:" + compressPath);

        }


    }


    List<String> ccList = new ArrayList<String>();

    @OnClick({R.id.img_back, R.id.qs, R.id.cs,  })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.qs:
                if (check == 0) {
                    //照片
                    tuijian();


                } else if (check == 1) {
//                    tuijian2();
                    //视频
                   }

                break;
            case R.id.cs:
                Intent intent = new Intent(this, ScanActivity.class);
                startActivityForResult(intent, 999);
                break;

        }
    }
    private String videoUri;
    private ImageView imageView;
    private String videoScreenshot;
//    public void go() {
//
////    不知道传入什么？用下面的参数就可以了
//
//
//        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
//                .doH264Compress(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
//                )
//                .setMediaBitrateConfig(new AutoVBRMode()
//                        .setVelocity(BaseMediaBitrateConfig.Velocity.ULTRAFAST)
//                )
//                .smallVideoWidth(480)
//                .smallVideoHeight(360)
//                .recordTimeMax(6 * 1000)
//                .maxFrameRate(20)
//                .minFrameRate(8)
//                .captureThumbnailsTime(1)
//                .recordTimeMin((int) (1.5 * 1000))
//                .build();
////                    MediaRecorderListener mListener=
//        MediaRecorderActivity.goSmallVideoRecorder(this, new MediaRecorderListener() {
//            @Override
//            public void onEncodeComplete(MediaRecorder mediaRecorder) {
//                st2 =mediaRecorder.getVIDEO_URI();
//                videoScreenshot = mediaRecorder.getVIDEO_SCREENSHOT();
//                if(st2!=null && videoScreenshot!=null) {
//                    Bitmap bitmap = BitmapFactory.decodeFile(videoScreenshot);
//                    sp.setImageBitmap(bitmap);
//                }
//            }
//        }, config);
//
//
//    }
    int q;
    StringBuilder stringBuilder = new StringBuilder();
    StringBuilder stringBuilder2 = new StringBuilder();
    public void tuijian2() {


        if (!TextUtils.isEmpty(st2)) {
            stringBuilder.setLength(0);
            stringBuilder2.setLength(0);
            showdialog();
            API.Upload(httpipdizhi + "uploads", "/" + tongxingzhi + "/" + dingdanhao , st2, st2.substring(st2.lastIndexOf("/")+1), canshu1,new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String st) {
                    Log.e(TAG, "xx" + st);
                    double fileOrFilesSize = Files.getFileOrFilesSize(st2, 1);
                    Log.e(TAG,""+ fileOrFilesSize);
                    stringBuilder2.append(fileOrFilesSize);
                    stringBuilder.append( st2.substring(st2.lastIndexOf("/")+1,st2.length()) );

                        up2( );

                }

                @Override
                public void onFalia(int code, String errst) {
                    Log.e(TAG, "xx" + errst);
                    Log.e(TAG, "上传失败了");
                    Toast.makeText(TJ_Activity.this, "" + errst, Toast.LENGTH_SHORT).show();
                    if (dialog != null ) {
                        dialog.dismiss();}

                }
            });

        } else {
            Toast.makeText( this, "请选择视频!", Toast.LENGTH_SHORT).show();

        }
    }
    public void tuijian() {


        if (selectList.size() == 0) {
            Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        ccList.clear();
        showdialog();
        q = 0;
        stringBuilder.setLength(0);
        stringBuilder2.setLength(0);
        for (int i = 0; i < selectList.size(); i++) {
            final int  X=i;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    up(selectList.get(finalI).getCompressPath());

                    final String format =   ""+ Math.random();
//                    httpipdizhi="http://192.168.10.218:9500/";


                    API.Upload(httpipdizhi + "uploads", "/" + tongxingzhi + "/" + dingdanhao , selectList.get( X).getCompressPath(), format + ".jpg",canshu1, new Okhttp.Objectcallback() {
                        @Override
                        public void onsuccess(String st) {
                            Log.e(TAG, "xx" + st);
                            double fileOrFilesSize = Files.getFileOrFilesSize(selectList.get(X).getCompressPath(), 1);
                            Log.e(TAG,""+ fileOrFilesSize);
                            stringBuilder2.append(fileOrFilesSize);
                            stringBuilder2.append("*");
                            stringBuilder.append(format + ".jpg");
                            stringBuilder.append("*");
//                            Toast.makeText(TJ_Activity.this, "" + st, Toast.LENGTH_SHORT).show();
                            q++;
                            if ( q == selectList.size() ) {
                                Log.e(TAG, "上传完了");
                                up();
                            } else {
                                Log.e(TAG, "上传没完了");
                            }
                        }

                        @Override
                        public void onFalia(int code, String errst) {
                            Log.e(TAG, "xx" + errst);
                            Log.e(TAG, "上传失败了");
                            Toast.makeText(TJ_Activity.this, "" + errst, Toast.LENGTH_SHORT).show();
                            if (dialog != null ) {
                                dialog.dismiss();}
                        }
                    });
                }
            }, 2000);


        }


    }

    KProgressHUD dialog;

    public void showdialog() {
        dialog = KProgressHUD.create(TJ_Activity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在上传中，请稍候")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();
    }
    public void up2( ) {
        if (dialog != null ) {
            dialog.dismiss();
            Log.e(TAG, "关闭了" + q);
            String dd = "http://www.zhikesys.top/appftpExcute.aspx?type=" + chulileixingtype + "&duijiema=" + duijiema + "&tongxingzheng=" + tongxingzhi + "&ordernumber=" + dingdanhao + "&ordernumber_self=" + dingdanzidingyibianhao + "&appipAddress=" + httpipdizhi + "&value1=" + canshu1 + "&value2=" + canshu2 + "&value3=" + canshu3 + "&value4=" + canshu4 + "&value5=" + canshu5 + "&usernameid=" + yonghuid + "&sizelist="+stringBuilder2+"&piclist=" + stringBuilder;
//                String dd = "http://www.zhikesys.top/appfinanceAddpic.aspx?duijiema=" + duijiema + "&id=" + dingdanhao + "&piclist=" + stringBuilder;
            Log.e(TAG, "dd:" + dd);
            Okhttp.get(dd, null, new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String result) {
                    Log.e(TAG, "qw1" + result);
                    String str = result.substring(result.indexOf("###") + 3, result.indexOf("***")).replace("^", "\"");
                    if (TextUtils.isEmpty(result)||str.equals("")) {
//                        show(str,0);
                        finish();
                    } else {
                        show(str,1);
//                        Toast.makeText(TJ_Activity.this, st, Toast.LENGTH_LONG).show();
                    }


                }

                @Override
                public void onFalia(int code, String errst) {
                    Log.e(TAG, "qw2" + errst);
                    Toast.makeText(TJ_Activity.this, errst, Toast.LENGTH_LONG).show();
                }
            });
        }


    }


    public void up() {
        if (dialog != null && selectList.size() == q) {
            dialog.dismiss();
            Log.e(TAG, "关闭了" + q);

            for (int i = 0; i < ccList.size(); i++) {
                Log.e("rrrr", ccList.get(i));

                stringBuilder.append(ccList.get(i));
                stringBuilder.append("*");
                Log.e("rrrr", "V" + ccList.size());

//                  123123123&id=第二个参数&piclist=5454_54.jpg*65465_5454.jpg
            }
            String dd = "http://www.zhikesys.top/appftpExcute.aspx?type=" + chulileixingtype + "&duijiema=" + duijiema + "&tongxingzheng=" + tongxingzhi + "&ordernumber=" + dingdanhao + "&ordernumber_self=" + dingdanzidingyibianhao + "&appipAddress=" + httpipdizhi + "&value1=" + canshu1 + "&value2=" + canshu2 + "&value3=" + canshu3 + "&value4=" + canshu4 + "&value5=" + canshu5 + "&usernameid=" + yonghuid + "&sizelist="+stringBuilder2+"&piclist=" + stringBuilder;
//                String dd = "http://www.zhikesys.top/appfinanceAddpic.aspx?duijiema=" + duijiema + "&id=" + dingdanhao + "&piclist=" + stringBuilder;
            Log.e(TAG, "dd:" + dd);
            Okhttp.get(dd, null, new Okhttp.Objectcallback() {
                @Override
                public void onsuccess(String result) {
                    Log.e(TAG, "qw1" + result);
                    String str = result.substring(result.indexOf("###") + 3, result.indexOf("***")).replace("^", "\"");
                    if (TextUtils.isEmpty(result)||str.equals("")) {
//                        show(str,0);
                        finish();
                    } else {
                        show(str,1);
//                        Toast.makeText(TJ_Activity.this, st, Toast.LENGTH_LONG).show();
                    }


                }

                @Override
                public void onFalia(int code, String errst) {
                    Log.e(TAG, "qw2" + errst);
                    Toast.makeText(TJ_Activity.this, errst, Toast.LENGTH_LONG).show();
                }
            });
        }


    }
public  void  show(String DD,final int type){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
              //设置标题
              builder.setTitle("提示");
              //设置提示消息
              builder.setMessage(DD);
              builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialogInterface, int i) {
//                      if (type==0) {
                          finish();
//                      } else {
//
//                      }

                  }
              });

              //显示dialog
              builder.show();
}

    public static String timeStamp() {
        long time = System.currentTimeMillis();
        String t = String.valueOf(time / 1000);
        return t;
    }
}
